package springboot.exception;

import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import springboot.domain.ExceptionReturn;
import springboot.domain.User;

@ControllerAdvice
public class GlobalException {

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public ExceptionReturn getBindException(BindException e) {
        System.out.println(e.getBindingResult().getFieldError().getDefaultMessage());
        ExceptionReturn exceptionReturn = new ExceptionReturn();
        exceptionReturn.setCode(300);
        exceptionReturn.setMessage(e.getBindingResult().getFieldError().getDefaultMessage());
        return exceptionReturn;
    }

    @ExceptionHandler(Exception.class)//抓取所有
    @ResponseBody
    public User getException(Exception e) {
        System.out.println("所有异常都进来");
        User user = new User();
        user.setId(1);
        user.setName("error");
        user.setAge(1);
        return user;
    }
}
